package com.queming.service;

import com.queming.core.entity.User;
import com.queming.core.exception.BizException;
import com.queming.core.exception.ExceptionType;
import com.queming.core.respository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 *
 * @author 陈词调
 * @date 2022/5/6
 */
public abstract class BaseService {

    @Autowired
    private UserRepository userRepository;


    protected User getCurrentUserEntity(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return findUserByUsername(authentication.getName());
    }

    protected User findUserByUsername(String username){
        Optional<User> user = userRepository.findByUsername(username);
        if (!user.isPresent()){
            throw new BizException(ExceptionType.USER_UNKNOW_ERROR);
        }
        return user.get();
    }
}
